//
//  CZServiceLogInfoController.m
//  TCProject
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "CZServiceLogInfoController.h"
#import "CZAddServiceLogCell.h"
#import "AccountManager.h"
#import "REMenu.h"


@interface CZServiceLogInfoController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *liangs;
@property (nonatomic, strong) NSArray *prices;

@property (nonatomic, strong) REMenu *featureMenu;
@property (nonatomic, strong) StylePrice *currentPrice;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@property (weak, nonatomic) IBOutlet UIView *topContainer;

@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UITextField *fangTextfield;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIButton *signAllButton;

@property (weak, nonatomic) IBOutlet UIButton *commitButton;
@property (weak, nonatomic) IBOutlet UILabel *h2;

- (IBAction)showFeature:(UITapGestureRecognizer *)sender;

- (IBAction)signAllAction:(id)sender;

- (IBAction)commitAction:(id)sender;

@end

@implementation CZServiceLogInfoController
- (REMenu *)featureMenu
{
    if (!_featureMenu) {
        _featureMenu = [[REMenu alloc] init];
    }
    return _featureMenu;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textView.layer.borderColor = [BMColor(235, 235, 235, 1) CGColor];
    self.textView.layer.borderWidth = 1.f;
    self.textView.layer.cornerRadius = 4.f;
    self.tableView.rowHeight = 44.f;
    self.tableView.allowsSelection = NO;
    
    if ([@"砼车" isEqualToString:_order.style1]) {
        [self loadCarInfo];
    } else {
        self.h2.text = @"泵距方量";
        self.topContainer.hidden = YES;
        self.topConstraint.priority = 800;
    }
    
    if (_log) {
        self.fangTextfield.text = [@(_log.volume) description];
        if (![BMUtils isEmptyString:_log.remarks]) {
            _textView.text = _log.remarks;
        }
    }
    
    [self getData];

}

- (void)loadCarInfo
{
    weakSelf(self);
    BMRequest *request = [BMRequest requestWithPath:@"/getTruckStyle1PriceList.htm" contentKey:@"TruckStyleList"];
    [ZDTruck postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == 1) {
            for (ZDTruck *truck in response.result) {
                if ([_order.style1 isEqualToString:truck.styleName]) {
                    self.prices = truck.stylePrice;
                }
            }
            NSMutableArray *items = [NSMutableArray array];
            for (int i = 0; i < _prices.count; i++) {
                StylePrice *price = _prices[i];
                if (_log && [_log.distance isEqualToString:[price condition]]) {
                    self.currentPrice = price;
                }
                
                REMenuItem *item = [[REMenuItem alloc] initWithTitle:nil image:nil highlightedImage:nil action:^(REMenuItem *item) {
                    weakSelf.currentPrice = item.price;
                }];
                item.price = _prices[i];
                [items addObject:item];
                
                if ([_order.condition isEqualToString:price.condition]) {
                    self.currentPrice = price;
                }
            }
            self.featureMenu.items = items;
        } else {
            [self showHint:@"获取车辆信息失败!"];
        }
    }];
}

- (void)getData
{
    BMRequest *request = [BMRequest requestWithPath:@"getPriceByTruckStyleName.htm"];
    request.params = @{@"truckStyleName": _order.style1 ? _order.style1 : @""};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.liangs = response.rawResult[@"serviceTypes"];
            [self.tableView reloadData];
        } else {
            [self showHint:response.msg];
        }
    }];
}

- (void)setCurrentPrice:(StylePrice *)currentPrice{
    _currentPrice = currentPrice;
    self.distanceLabel.text = _currentPrice.condition;
}

- (IBAction)showFeature:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
    [self.featureMenu showInView:self.view yOffset:64.f];
}

- (IBAction)signAllAction:(UIButton* )sender {
    sender.selected = !sender.selected;
}

- (IBAction)commitAction:(id)sender {
    
    NSString *fang = self.fangTextfield.text;
    if ([BMUtils isEmptyString:fang]) {
        [self showHint:@"请填写合适方量"];
        return;
    }
    
    double total = 0;
    for (int i = 0; i < _liangs.count; i++) {
        CZAddServiceLogCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        total += [cell.contentTextfield.text doubleValue];
    }
    
    if ([@"砼车" isEqualToString:_order.style1]) {
        total += [fang doubleValue] * ([_currentPrice.price doubleValue] + [_order.changeUnitPrice doubleValue]);
    } else {
        total += [fang doubleValue] * (_order.unitPrice + [_order.changeUnitPrice doubleValue]);
    }
    NSString *msg = [NSString stringWithFormat:@"确认本次服务为%.2f元?", total];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:cancleAction];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"orderId": @(_order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID), @"volume": fang}];
        
        if ([@"砼车" isEqualToString:_order.style1]) {
            if (_currentPrice) {
                params[@"priceId"] = @(_currentPrice.ID);
                params[@"distance"] = _currentPrice.condition;
            }
        }
        
        NSString *content = self.textView.text;
        if (![BMUtils isEmptyString:content]) {
            params[@"remarks"] = content;
        } else {
            params[@"remarks"] = @"";
        }
        
        NSMutableArray *others= [NSMutableArray array];
        for (int i = 0; i < _liangs.count; i++) {
            CZAddServiceLogCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            NSString *charge = cell.contentTextfield.text;
            if (![BMUtils isEmptyString:charge]) {
                NSDictionary *serviceType = _liangs[i];
                [others addObject:[NSString stringWithFormat:@"{typeId:%@, typeName:\"%@\", charge:%@}", serviceType[@"id"], serviceType[@"serviceTypeName"], charge]];
            }
        }
        
        if (others.count) {
            NSMutableString *str = [NSMutableString stringWithString:@"["];
            for (NSString *one in others) {
                [str appendFormat:@"%@,", one];
            }
            params[@"serviceTypeCharge"] = [[str substringToIndex:str.length - 1] stringByAppendingString:@"]"];
        }
        
        if (_log) {
            params[@"id"] = @(_log.ID);
        }
        
        params[@"checked"] = @0;
        
        BMRequest *request = [BMRequest requestWithPath:_log ? @"serviceLog/update.htm" : @"serviceLog/add.htm"];
        request.params = params;
        [self showHudWithhint:kDefaultMessage];
        [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
            [self hideHud];
            if (response.status == kResultOK) {
                NSArray *vcs = self.navigationController.childViewControllers;
                UIViewController *vc = vcs[vcs.count - 2];
#pragma clang diagnostic ignored "-Wundeclared-selector"
                if ([vc respondsToSelector:@selector(updateServiceLog)]) {
                    [vc performSelector:@selector(updateServiceLog)];
                }
#pragma clang diagnostic pop
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [self showHint:response.msg];
            }
        }];
    }];
    [alertVC addAction:okAction];
    [self presentViewController:alertVC animated:YES completion:nil];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _liangs.count;
}

- (UITableViewCell* )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CZAddServiceLogCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.titleLabel.text = _liangs[indexPath.row][@"serviceTypeName"];
    [_log.typeCharges enumerateObjectsUsingBlock:^(TypeCharge *type, NSUInteger idx, BOOL *stop) {
        if ([cell.titleLabel.text isEqualToString:type.typeName]) {
            cell.contentTextfield.text = [@(type.charge) description];
            *stop = YES;
        }
    }];
    return cell;
    
}


@end
